import React, {PureComponent} from 'react';
import PropTypes from 'prop-types';
import {Row, Col, Form, Button, Divider, Table, message as msg, Modal} from 'antd';
import {PAGE, TABLE, PAGINATION_OPTIONS, FORM_OPTIONS} from '../constants';
import TextInput from 'Shared/components/TextInput';
import SelectAlert from '../common/SelectAlert';
import WrappedSelect from '../common/WrappedSelect';
import TextArea from 'Shared/components/TextArea';
import {computeSelectedRows, conventSorter} from './utils';
import {conventEnumValueToString} from '../utils';
import styles from './style.css';
import {getSaleProformaInvoices} from './api';
import {saleOrderTransportType, saleOrderPriceTerms, paymentType, currency} from '../Enum';
import {injectIntl, language} from './intl';
import {unionBy, union} from 'lodash';
const FormItem = Form.Item;
const MultiSelectAlert = SelectAlert.Multi;
const saleOrderTransportTypList = saleOrderTransportType.toList(language);
const salesOrderPriceTermsList = saleOrderPriceTerms.toList(language);
const paymentTypeList = paymentType.toList(language);
const currencyList = currency.toList(language);

class CBUSelectPanel extends PureComponent {
    state = {
        code: [],
        batchNumber: [],
        currency: this.props.currency,
        paymentType: this.props.paymentType,
        salesOrderPriceTerms: this.props.salesOrderPriceTerms,
        transportType: this.props.transportType,
        tradeMethodId: this.props.tradeMethodId,
        isFetching: false,
        data: {},
        message: '',
        pageIndex: PAGE.index,
        pageSize: PAGE.smallSize,
        currentCondition: {},
        selectedRowKeys: [],
        selectedRows: [],
        content: [],
    }
    
    handleTableChange = (pagination, filters, sorter) => {
        const oldCondition = {...this.state.currentCondition};
        if(pagination.current - 1 === oldCondition.pageIndex && pagination.pageSize === oldCondition.pageSize) {
            const sortOptions = conventSorter(sorter);
            const condition = Object.assign({}, oldCondition, sortOptions, {
                pageIndex: pagination.current - 1
            });
            this.onQuery(condition);
            this.setState({
                sortField: sortOptions.sortField,
                isDesc: sortOptions.isDesc
            });
        }
    }

    handleFilterPressEnter = (value, name) => {
        this.setState({[name]: value}, this.onClickSearchBtn);
    }
    flatten = arr => {
        const length = arr.length;
        const newArr = [];

        for(let i = 0; i < length; i++) {
            const childLength = arr[i].details && arr[i].details.length;
            let item = {};
            if(childLength > 0)
                for(let j = 0; j < childLength; j++) {
                    item = {
                        piId: arr[i].id,
                        piCode: arr[i].piCode,
                        piSubmitTime: arr[i].details[j].piSubmitTime,
                        id: arr[i].details[j].id,
                        descriptionOfGoods: arr[i].details[j].descriptionOfGoods,
                        kdBomCode: arr[i].details[j].kdBomCode,
                        quantity: arr[i].details[j].quantity,
                        price: arr[i].details[j].price,
                        batchNumber: arr[i].batchNumber,
                        currency: arr[i].currency,
                        transportType: arr[i].transportType,
                        paymentType: arr[i].paymentType,
                        salesOrderPriceTerms: arr[i].salesOrderPriceTerms,
                        tradeMethodId: arr[i].tradeMethodId,
                        tradeMethodName: this.props.tradeMethodName,
                        dealerCode: this.props.dealerCode,
                        brandCode: this.props.brandCode,
                    };
                    newArr.push(item);
                }
            else
                newArr.push(arr[i]);
        }
    
        return newArr;
    }
    onQuery = condition => {
        this.setState({isFetching: true});
        getSaleProformaInvoices(condition)
            .then(res => {
                if(res.ok)
                    this.setState({
                        isFetching: false,
                        message: '',
                        data: res.data,
                        content: res.data.content && this.flatten(res.data.content),
                        currentCondition: condition
                    });
                else
                    this.setState({
                        isFetching: false,
                        data: [],
                        message: res.message
                    });
            });
    }

    onClickSearchBtn = () => {
        const condition = {
            code: this.state.code,
            batchNumber: this.state.batchNumber,
            brandId: this.props.brandId,
            dealerId: this.props.dealerId,
            businessType: 2,
            transportType: this.state.transportType,
            currency: this.state.currency,
            tradeMethodId: this.props.tradeMethodId,
            paymentType: this.state.paymentType,
            salesOrderPriceTerms: this.state.salesOrderPriceTerms,
            pageIndex: PAGE.index,
            pageSize: this.state.pageSize,
            sortField: this.state.sortField,
            isDesc: this.state.isDesc,

        };
        this.onQuery(condition);
    }

    onPageIndexChange = current => {
        const condition = {...this.state.currentCondition};
        condition.pageIndex = current - 1;
        this.onQuery(condition);
    }

    onPageSizeChange = (current, pageSize) => {
        const condition = {...this.state.currentCondition};
        condition.pageIndex = PAGE.index;
        condition.pageSize = pageSize;
        this.onQuery(condition);
        this.setState({
            pageSize
        });
    }

    onChange = (value, name) => {
        this.setState({[name]: value});
    }

    onClickReset = () => {
        this.setState({
            code: [],
            batchNumber: [],
            currency: '',
            paymentType: '',
            salesOrderPriceTerms: '',
            transportType: '',
            tradeMethodId: '',
        });
    }

    onChangeRadio = (selectedRowKeys, selectedRows) => {
        this.setState({
            selectedRowKeys,
            selectedRows
        });
    }

    onCloseTag = () => {
        this.setState({
            selectedRowKeys: [],
            selectedRows: []
        });
    }

    onSubmit = () => {
        if(!this.state.selectedRows.length)
            return msg.warn(this.props.intl.formatMessage({
                id: 'KDSelectPanel.validate.getSaleProformaInvoices',
                defaultMessage: '请选择PI形式发票信息'
            }));
        const groupByRows = unionBy(union(this.state.selectedRows, this.props.currentSelectRowkeys.filter(v => !''.includes(v.piCode))),
            'currency', 'paymentType', 'salesOrderPriceTerms', 'transportType');
        if(groupByRows.length > 1)
            return msg.warn(this.props.intl.formatMessage({
                id: 'KDSelectPanel.validate.groupByRows',
                defaultMessage: '只有相同品牌、总代、币种、贸易方式、付款方式、价格条款、运输方式的PI才能合并'
            }));
        this.props.onSelect(this.state.selectedRows, this.props.selectKey);
    }
    onClickProductGroup = () => {
        this.state({
            showProductGroupPanel: true
        });
    }
    render() {
        const {formatMessage} = this.props.intl;
        const {isFetching, data, content} = this.state;
        const {pageIndex, pageSize} = this.state.currentCondition;
        const columns = [
            {
                title: formatMessage({
                    id: 'KDSelectPanel.column.piCode',
                    defaultMessage: 'PI编号'
                }),
                sorter: true,
                dataIndex: 'piCode'
            }, {
                title: formatMessage({
                    id: 'KDSelectPanel.column.brandCode',
                    defaultMessage: '品牌'
                }),
                dataIndex: 'brandCode',
            }, {
                title: formatMessage({
                    id: 'KDSelectPanel.column.dealerCode',
                    defaultMessage: '总代号'
                }),
                dataIndex: 'dealerCode',
            }, {
                title: formatMessage({
                    id: 'KDSelectPanel.column.salesOrderPriceTerms',
                    defaultMessage: '价格条款'
                }),
                dataIndex: 'salesOrderPriceTerms',
                render: text => conventEnumValueToString(saleOrderPriceTerms, text)
            }, {
                title: formatMessage({
                    id: 'KDSelectPanel.column.paymentType',
                    defaultMessage: '付款方式'
                }),
                dataIndex: 'paymentType',
                render: text => conventEnumValueToString(paymentType, text)
            }, {
                title: formatMessage({
                    id: 'KDSelectPanel.column.tradeMethodName',
                    defaultMessage: '贸易方式'
                }),
                dataIndex: 'tradeMethodName'
            }, {
                title: formatMessage({
                    id: 'KDSelectPanel.column.transportType',
                    defaultMessage: '运输方式'
                }),
                dataIndex: 'transportType',
                render: text => conventEnumValueToString(saleOrderTransportType, text)
            }, {
                title: formatMessage({
                    id: 'KDSelectPanel.column.currency',
                    defaultMessage: '币种'
                }),
                dataIndex: 'currency',
                render: text => conventEnumValueToString(currency, text)
            }, {
                title: formatMessage({
                    id: 'CBUSelectPanel.column.batchNumber',
                    defaultMessage: '批次号'
                }),
                dataIndex: 'batchNumber',
            }, {
                title: formatMessage({
                    id: 'KDSelectPanel.column.descriptionOfGoods',
                    defaultMessage: '产品描述'
                }),
                dataIndex: 'descriptionOfGoods',
            }, {
                title: formatMessage({
                    id: 'KDSelectPanel.column.kdBomCode',
                    defaultMessage: 'KDBOM'
                }),
                dataIndex: 'kdBomCode',
            }, {
                title: formatMessage({
                    id: 'KDSelectPanel.column.quantity',
                    defaultMessage: '数量'
                }),
                dataIndex: 'quantity',
            }, {
                title: formatMessage({
                    id: 'KDSelectPanel.column.price',
                    defaultMessage: '单价'
                }),
                dataIndex: 'price',
            }
        ];
            

        const pagination = {
            total: data.totalElements,
            current: pageIndex + 1,
            pageSize,
            onShowSizeChange: this.onPageSizeChange,
            onChange: this.onPageIndexChange,
            ...PAGINATION_OPTIONS
        };
        const rowSelection = {
            selectedRowKeys: this.state.selectedRowKeys,
            onChange: (selectedRowKeys, selectedRows) => {
                const rows = computeSelectedRows(this.state.selectedRowKeys, this.state.selectedRows, selectedRowKeys, selectedRows);
                this.setState({
                    selectedRowKeys,
                    selectedRows: rows
                });
            },
            getCheckboxProps: record => ({
                disabled: this.props.currentSelectRowkeys.some(item => item.piDetailId === record.id) || record.quantity <= 0
            })
        };
        return (
            <Modal
                title={formatMessage({
                    id: 'KDSelectPanel.show.getSaleProformaInvoices',
                    defaultMessage: 'KD形式发票查询'
                })}
                width="60%"
                maskClosable={false}
                footer={null}
                destroyOnClose={true}
                wrapClassName={styles.dataSelectModal}
                visible={true}
                onCancel={this.props.onCancel}>
                <Row className="form-standard">
                    <Col {...FORM_OPTIONS.col}>
                        <FormItem label={formatMessage({
                            id: 'KDSelectPanel.code',
                            defaultMessage: 'PI编号'
                        })} {...FORM_OPTIONS.item}>
                            <TextArea
                                name="code"
                                placeholder={formatMessage({
                                    id: 'KDSelectPanel.form.code.placeholder',
                                    defaultMessage: '最多输入1000个PI编号，以回车隔开'
                                })}
                                value={this.state.code}
                                onBlur={this.onChange} />
                        </FormItem>
                    </Col>
                    <Col {...FORM_OPTIONS.col}>
                        <FormItem label={formatMessage({
                            id: 'KDSelectPanel.batchNumber',
                            defaultMessage: '批次号'
                        })} {...FORM_OPTIONS.item}>
                            <TextArea
                                name="batchNumber"
                                placeholder={formatMessage({
                                    id: 'KDSelectPanel.form.batchNumber.placeholder',
                                    defaultMessage: '最多输入1000个批次号，以回车隔开'
                                })}
                                value={this.state.batchNumber}
                                onBlur={this.onChange} />
                        </FormItem>
                    </Col>
                    <Col {...FORM_OPTIONS.col}>
                        <FormItem label={this.props.intl.formatMessage({
                            id: 'KDSelectPanel.form.salesOrderPriceTerms',
                            defaultMessage: '价格条款'
                        })} className={styles['label-wrap']} {...FORM_OPTIONS.item}>
                            <WrappedSelect
                                allowClear
                                name="salesOrderPriceTerms"
                                value={this.state.salesOrderPriceTerms}
                                options={salesOrderPriceTermsList}
                                onChange={this.onChange} />
                        </FormItem>
                    </Col>
                    <Col {...FORM_OPTIONS.col}>
                        <FormItem label={this.props.intl.formatMessage({
                            id: 'KDSelectPanel.form.paymentType',
                            defaultMessage: '付款方式'
                        })} className={styles['label-wrap']} {...FORM_OPTIONS.item}>
                            <WrappedSelect
                                allowClear
                                name="paymentType"
                                value={this.state.paymentType}
                                options={paymentTypeList}
                                onChange={this.onChange} />
                        </FormItem>
                    </Col>
                    <Col {...FORM_OPTIONS.col}>
                        <FormItem label={this.props.intl.formatMessage({
                            id: 'KDSelectPanel.form.tradeMethodId',
                            defaultMessage: '贸易方式'
                        })} className={styles['label-wrap']} {...FORM_OPTIONS.item}>
                            <WrappedSelect
                                allowClear
                                name="tradeMethodId"
                                value={this.state.tradeMethodId}
                                options={this.props.tradeMethodList}
                                onChange={this.onChange}/>
                        </FormItem>
                    </Col>
                    <Col {...FORM_OPTIONS.col}>
                        <FormItem label={this.props.intl.formatMessage({
                            id: 'KDSelectPanel.form.transportType',
                            defaultMessage: '运输方式'
                        })} className={styles['label-wrap']} {...FORM_OPTIONS.item}>
                            <WrappedSelect
                                allowClear
                                name="transportType"
                                value={this.state.transportType}
                                options={saleOrderTransportTypList}
                                onChange={this.onChange} />
                        </FormItem>
                    </Col>
                    <Col {...FORM_OPTIONS.col}>
                        <FormItem label={this.props.intl.formatMessage({
                            id: 'KDSelectPanel.form.currency',
                            defaultMessage: '币种'
                        })} className={styles['label-wrap']} {...FORM_OPTIONS.item}>
                            <WrappedSelect
                                allowClear
                                name="currency"
                                value={this.state.currency}
                                options={currencyList}
                                onChange={this.onChange} />
                        </FormItem>
                    </Col>
                    <Col {...FORM_OPTIONS.col} className={styles['inline-button']}>
                        <Button
                            type="primary"
                            loading={isFetching}
                            onClick={this.onClickSearchBtn}>
                            {formatMessage({
                                id: 'KDSelectPanel.btn.query',
                                defaultMessage: '查询'
                            })}
                        </Button>
                        <Button key="clear" onClick={this.onClickReset}>{formatMessage({
                            id: 'KDSelectPanel.btn.reset',
                            defaultMessage: '重置'
                        })}</Button>
                    </Col>
                </Row>
                <Divider className={styles.divider}/>
                <MultiSelectAlert data={this.state.selectedRows}
                    onConfirm={this.onSubmit}
                    onDelete={this.onCloseTag}
                    onDeleteAll={this.onCloseTag}/>
                <Table
                    className="white-space-nowrap"
                    rowKey="id"
                    dataSource={content}
                    rowClassName={styles.tableCursor}
                    columns={columns}
                    loading={isFetching}
                    pagination={pagination}
                    onChange={this.handleTableChange}
                    rowSelection={rowSelection}
                    {...TABLE}/>
            </Modal >
        );
    }
}

CBUSelectPanel.propTypes = {
    currentSelectRowkeys: PropTypes.array.isRequired,
    onSelect: PropTypes.func.isRequired,
    brandCode: PropTypes.string,
    brandId: PropTypes.string,
    currency: PropTypes.number,
    dealerCode: PropTypes.string,
    dealerId: PropTypes.string,
    intl: PropTypes.object,
    paymentType: PropTypes.number,
    salesOrderPriceTerms: PropTypes.number,
    tradeMethodId: PropTypes.string,
    tradeMethodList: PropTypes.array,
    tradeMethodName: PropTypes.string,
    transportType: PropTypes.number,
    onCancel: PropTypes.func,
};

export default injectIntl(CBUSelectPanel);
